<template>
  <div class="flight-search">
    <h2>{{ title }}</h2>
    <div class="search-form">
      <div class="form-row">
        <div class="form-group">
          <label>出发城市</label>
          <input
            v-model="searchParams.departureCity"
            placeholder="请输入出发城市（可选）"
            @keyup.enter="handleSearch"
            @input="handleInputChange"
          />
        </div>
        <div class="form-group">
          <label>到达城市</label>
          <input
            v-model="searchParams.arrivalCity"
            placeholder="请输入到达城市（可选）"
            @keyup.enter="handleSearch"
            @input="handleInputChange"
          />
        </div>
        <div class="form-group">
          <label>出发时间</label>
          <input
            v-model="searchParams.departureTime"
            type="datetime-local"
            placeholder="请选择出发时间（可选）"
            @keyup.enter="handleSearch"
            @input="handleInputChange"
          />
        </div>
      </div>
      <button @click="handleSearch" class="search-button" :disabled="loading">
        {{ loading ? '搜索中...' : '搜索航班' }}
      </button>
    </div>

    <!-- 城市建议下拉框 -->
    <div
      v-if="citySuggestions.length > 0"
      class="city-suggestions"
      :class="{ 'departure': activeInput === 'departure', 'arrival': activeInput === 'arrival' }"
    >
      <div
        v-for="city in citySuggestions"
        :key="city"
        class="suggestion-item"
        @click="selectCity(city)"
      >
        {{ city }}
      </div>
    </div>
  </div>
</template>

<script>
import api from '../api'

export default {
  name: 'FlightSearch',
  props: {
    // 标题
    title: {
      type: String,
      default: '机票查询'
    },
    // 是否自动搜索（输入时自动搜索）
    autoSearch: {
      type: Boolean,
      default: false
    },
    // 初始搜索参数
    initialParams: {
      type: Object,
      default: () => ({
        departureCity: '',
        arrivalCity: '',
        departureTime: ''
      })
    }
  },
  emits: ['search', 'loading-change'],
  data() {
    return {
      searchParams: {
        departureCity: '',
        arrivalCity: '',
        departureTime: ''
      },
      loading: false,
      activeInput: null,
      citySuggestions: [],
      searchTimer: null,
    }
  },
  mounted() {
    // 初始化搜索参数
    this.searchParams = { ...this.initialParams }
  },
  methods: {
    async handleSearch() {
      if (!this.searchParams.departureCity.trim() && !this.searchParams.arrivalCity.trim()) {
        alert('请输入出发城市或到达城市')
        return
      }

      this.loading = true
      this.$emit('loading-change', true)
      this.citySuggestions = []

      try {
        // 构建搜索参数
        const params = {}
        if (this.searchParams.departureCity.trim()) {
          params.departureCity = this.searchParams.departureCity.trim()
        }
        if (this.searchParams.arrivalCity.trim()) {
          params.arrivalCity = this.searchParams.arrivalCity.trim()
        }
        if (this.searchParams.departureTime) {
          params.departureTime = this.searchParams.departureTime
        }

        // 执行模糊搜索
        const response = await api.get('/flights/search', { params })

        this.$emit('search', {
          results: response.data,
          params: { ...this.searchParams }
        })
      } catch (error) {
        console.error('搜索航班失败:', error)
        alert('搜索航班失败，请稍后重试')
        this.$emit('search', {
          results: [],
          params: { ...this.searchParams },
          error: error
        })
      } finally {
        this.loading = false
        this.$emit('loading-change', false)
      }
    },

    handleInputChange(event) {
      const inputElement = event.target
      const inputType = inputElement.placeholder.includes('出发') ? 'departure' : 'arrival'
      const value = inputElement.value.trim()

      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }

      // 如果有输入内容，显示城市建议
      if (value.length > 0) {
        this.activeInput = inputType
        this.searchTimer = setTimeout(() => {
          this.filterCities(value)
        }, 300)
      } else {
        this.citySuggestions = []
        this.activeInput = null
      }

      // 自动搜索功能
      if (this.autoSearch) {
        this.searchTimer = setTimeout(() => {
          if (this.searchParams.departureCity.trim() || this.searchParams.arrivalCity.trim()) {
            this.handleSearch()
          }
        }, 1000)
      }
    },

    filterCities(query) {
      // 模糊匹配城市名
      const filtered = this.allCities.filter(city =>
        city.toLowerCase().includes(query.toLowerCase()) ||
        city.includes(query)
      )

      // 限制建议数量
      this.citySuggestions = filtered.slice(0, 8)
    },

    selectCity(city) {
      if (this.activeInput === 'departure') {
        this.searchParams.departureCity = city
      } else if (this.activeInput === 'arrival') {
        this.searchParams.arrivalCity = city
      }

      this.citySuggestions = []
      this.activeInput = null

      // 如果有城市输入，自动搜索
      if (this.autoSearch && (this.searchParams.departureCity || this.searchParams.arrivalCity)) {
        setTimeout(() => {
          this.handleSearch()
        }, 100)
      }
    },

    // 重置搜索参数
    resetSearch() {
      this.searchParams = {
        departureCity: '',
        arrivalCity: '',
        departureTime: ''
      }
      this.citySuggestions = []
      this.activeInput = null
    },

    // 设置搜索参数
    setParams(params) {
      this.searchParams = { ...this.searchParams, ...params }
    }
  }
}
</script>

<style scoped>
.flight-search {
  position: relative;
  width: 100%;
}

.flight-search h2 {
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
  color: #333;
}

.search-form {
  background-color: #f8f9fa;
  padding: 1.5rem;
  border-radius: 8px;
  margin-bottom: 2rem;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
  margin-bottom: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #555;
}

.form-group input {
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: #003366;
  box-shadow: 0 0 0 2px rgba(0, 51, 102, 0.1);
}

.search-button {
  padding: 0.75rem 1.5rem;
  background-color: #003366;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  width: fit-content;
  transition: background-color 0.3s ease;
}

.search-button:hover:not(:disabled) {
  background-color: #002244;
}

.search-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.search-tip {
  background-color: #e3f2fd;
  color: #1565c0;
  padding: 0.5rem 0.75rem;
  border-radius: 4px;
  font-size: 0.9rem;
  margin-bottom: 1rem;
  border-left: 4px solid #1976d2;
}

/* 城市建议下拉框 */
.city-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  z-index: 100;
  max-height: 200px;
  overflow-y: auto;
  margin-top: 4px;
}

.city-suggestions.departure {
  margin-top: -50px;
}

.city-suggestions.arrival {
  margin-top: -100px;
}

.suggestion-item {
  padding: 0.75rem 1rem;
  cursor: pointer;
  transition: background-color 0.2s ease;
  border-bottom: 1px solid #f0f0f0;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-item:hover {
  background-color: #f8f9fa;
}

.suggestion-item:first-child {
  border-radius: 4px 4px 0 0;
}

.suggestion-item:last-child {
  border-radius: 0 0 4px 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
  }

  .search-form {
    padding: 1rem;
  }

  .flight-search h2 {
    font-size: 1.5rem;
  }
}

@media (max-width: 480px) {
  .form-group input {
    padding: 0.5rem;
    font-size: 0.9rem;
  }

  .search-button {
    width: 100%;
    padding: 0.75rem;
  }
}
</style>